package com.bookrecommendation.client.web;

import java.util.Arrays;
import java.util.HashMap;

import com.bookrecommendation.client.GWTEntryPoint;
import com.bookrecommendation.client.facebook.FacebookImage;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

public class PopupBooks extends PopupPanel {

	public PopupBooks() {

		VerticalPanel vp = new VerticalPanel();

		vp.clear();

		vp.setSpacing(5);

		addContents(vp);

		this.setAutoHideEnabled(true);
		this.add(vp);
		this.center();
		this.show();
	}

	private void addContents(final VerticalPanel vp) {

		vp.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);

		Anchor refresh = new Anchor("Refresh");
		refresh.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {

				vp.clear();

				addContents(vp);
			}
		});

		vp.add(refresh);

		vp.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);

		vp.add(new Label("My Books"));

		vp.add(booksPanel(GWTEntryPoint.facebookUserBooks));

		vp.add(new Label("My Top Friend's Books"));

		vp.add(booksPanel(GWTEntryPoint.facebookFriendsBooks));

		vp.add(new Label("Top App Books"));

		vp.add(booksPanel(GWTEntryPoint.facebookTopBooks));

		vp.add(new Label("Top App Recommended Books"));

		vp.add(booksPanel(GWTEntryPoint.facebookTopBooksRecommended));
	}

	private HorizontalPanel booksPanel(HashMap<String, Integer> books) {

		HorizontalPanel hp = new HorizontalPanel();

		hp.setSpacing(3);

		Object[] booksSorted = books.values().toArray();

		Arrays.sort(booksSorted);

		int last5 = 0;
		if (booksSorted.length > 10) {

			last5 = Integer.parseInt(booksSorted[booksSorted.length - 10]
					.toString());
		} else {

			if (booksSorted.length > 0) {

				last5 = Integer.parseInt(booksSorted[0].toString());
			}
		}

		int i = 0;

		for (String bookID : books.keySet()) {

			if (i < 10 && books.get(bookID) >= last5) {

				String image = FacebookImage.getString(bookID, "");

				HTML book = new HTML("<br><br>" + image + "<br>"
						+ books.get(bookID));

				hp.add(book);

				i++;
			}
		}

		return hp;
	}
}
